{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# JavaScript 表单验证"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## JavaScript 表单验证\n",
    "JavaScript 可用来在数据被送往服务器前对 HTML 表单中的这些输入数据进行验证。\n",
    "\n",
    "表单数据经常需要使用 JavaScript 来验证其正确性：\n",
    "\n",
    "- 验证表单数据是否为空？\n",
    "- 验证输入是否是一个正确的email地址？\n",
    "- 验证日期是否输入正确？\n",
    "- 验证表单输入内容是否为数字型？"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "function validateForm(x){\n",
    "//   var x=document.forms[\"myForm\"][\"fname\"].value;\n",
    "    if (x==null || x==\"\"){\n",
    "        console.log(\"必须填写\");\n",
    "        return false;\n",
    "    }else{\n",
    "        console.log(\"通过\");\n",
    "    }\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "必须填写\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "false"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "validateForm();"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## E-mail 验证\n",
    "输入的数据必须包含 @ 符号和点号(.)。同时，@ 不可以是邮件地址的首字符，并且 @ 之后需有至少一个点号"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "function validateForm(x){\n",
    "//     var x=document.forms[\"myForm\"][\"email\"].value;\n",
    "    var atpos=x.indexOf(\"@\");\n",
    "    var dotpos=x.lastIndexOf(\".\");\n",
    "/*    \n",
    "    dotpos<atpos+2:“@”和“.”之间存在至少一个字符\n",
    "    dotpos+2>=x.length: “.”后面至少存在连个字符\n",
    "*/\n",
    "    if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length){\n",
    "        console.log(\"不是一个有效的 e-mail 地址\");\n",
    "        return false;\n",
    "    }else{\n",
    "        console.log(\"yes\");\n",
    "    }\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "yes\n"
     ]
    }
   ],
   "source": [
    "validateForm('ds@2.cn')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Javascript (Node.js)",
   "language": "javascript",
   "name": "javascript"
  },
  "language_info": {
   "file_extension": ".js",
   "mimetype": "application/javascript",
   "name": "javascript",
   "version": "13.13.0"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
